import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAccountStore = defineStore('account', () => {
  const isLoggedIn = ref(false)
  const username = ref('')

  //登录
  function login(token, user) {
    isLoggedIn.value = true
    username.value = user
    localStorage.setItem('token', token)
    localStorage.setItem('username', user)
  }

  //退出
  function logout() {
    isLoggedIn.value = false
    username.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }

  //恢复登录状态
  function restoreLoginState() {
    const token = localStorage.getItem('token')
    const user = localStorage.getItem('username')
    if (token && user) {
      isLoggedIn.value = true
      username.value = user
    }
  }

  return {
    isLoggedIn,
    username,
    login,
    logout,
    restoreLoginState
  }
})